/*
 * Copyright (c) 2019. Mikes. All rights reserved.
 *
 * You can contact me with sending email to bWlrZXNfMjAxMkAxNjMuY29t for more information!
 */

package com.climber.android.util

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import com.climber.android.R
import io.ganguo.library.mvp.util.ToastHelper
import io.library.android.net.NetworkManager
import java.util.*

/**
 * @author Mikes
 * @date 2018-5-28
 */
object ExitUtil {
    private var isExit = false

    /**
     * 双击退出函数
     *
     * @param context
     */
    fun exitByDoublePressed(context: Context) {
        if (!isExit) {
            isExit = true // 准备退出
            ToastHelper.toastMessage(R.string.click_double_to_exit)
            val tExit = Timer()
            tExit.schedule(object : TimerTask() {
                override fun run() {
                    isExit = false // 取消退出
                }
            }, 2000) // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务
        } else {
            exit(context)
        }
    }

    /**
     * 返回Launcher
     * @param context
     */
    fun exitGoLauncher(context: Context) {
        val home = Intent(Intent.ACTION_MAIN)
        home.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
        home.addCategory(Intent.CATEGORY_HOME)
        context.startActivity(home)
    }

    /**
     * 退出
     *
     * @param context
     */
    private fun exit(context: Context) {
        if(context is AppCompatActivity){
            NetworkManager.getDefault().unregisterAllObservers()

            context.finish()
        }
    }
}